package com.ty.filter;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/*",filterName = "traceIdFilter")
public class TraceIdFilter implements Filter {
    private static final String TRACE_ID = "traceId";
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest =    (HttpServletRequest)request;
        String traceId = httpServletRequest.getHeader(TRACE_ID);
        //如果前端请求头不传，那就给一个唯一的traceId
        if(ObjectUtil.isEmpty(traceId)){
            traceId = UUID.fastUUID().toString();
        }



        MDC.put(TRACE_ID, traceId);
        chain.doFilter(request, response);//接着往下走
    }
}
